import React  from 'react'
import { Card, Input, Form,Cascader,Upload,Button, message } from 'antd'
import { LeftOutlined  } from '@ant-design/icons'
import LinkButton from '@/components/link-button'
import { reqCategorys, reqAddUpdateProduct  } from '@api/product'
import PicturesWall from './picture-wall'
import RichTextEditor from './rich-text-editor'
import { validate_password } from '../../utils/validate'
const options = [
    {
        value: 'zhejiang',
        label: 'Zhejiang',
        isLeaf: false,
    },
    {
        value: 'jiangsu',
        label: 'Jiangsu',
        isLeaf: false,
    },
    {
        value: 'haha',
        label: 'abc',
        isLeaf: true,
    },
];
export default class addUpdate extends  React.Component {
    
    state = {
        options:options
    }
    PicturesWall = React.createRef()
    RichTextEditor = React.createRef()

    componentDidMount(){
        this.getCategorys('0')
    }
    componentWillMount(){
        // 取出携带的state
        const product = this.props.location.state
        // 保存是否更新的标识
        this.isUpdate = !!product
        // 保存商品
        this.product = product || {}
    }
    getCategorys=async (parentId)=>{
       const result = await reqCategorys(parentId)
       if(result.status===0){
            // 如果是第一分类列表
        if(parentId==='0'){
            const options=result.data.map(op=>({
                value:op._id,
                label:op.name,
                isLeaf:false
        }))
        const {isUpdate,product} = this
        const {pCategoryId,categoryId} = product 
        if(isUpdate && pCategoryId != '0'){
        //   获取对应的二级分类列表
          const subCategories = await this.getCategorys(pCategoryId)
        //   生成二级下拉列表的options
          const childOptions = subCategories.map(item=>({
                value:item._id,
                label:item.name,
                isLeaf:true
          }))
        //   对应返回 关联到对应的一级option上
        const targetOption = options.find(option=>{return option.value===pCategoryId})
        //   再关联到一级option
        targetOption.children = childOptions
        }
        // 生成options数组放到this.state
        this.setState({options:options})
        }else{
            return result.data  // 返回二级列表--》当前async函数返回的promise就会成功且value为categorys
        }
       }
    }
     

    onFinish =async (values) => {
        // 进行表单验证，如果通过了，才发送请求
        const {name, desc, price,classfy} = values
        //  获取到了子组件直接去使用子组件的方法并获取返回值
        const imgs = this.PicturesWall.current.getImgs()
        const detail = this.RichTextEditor.current.getDetail()
        let pCategoryId,categoryId
        if(classfy.length===1){
            pCategoryId = '0'
            categoryId = classfy[1]
        }else{
            pCategoryId = classfy[0]
            categoryId = classfy[1]
        }
        const product = {name, desc, price, imgs, detail, pCategoryId, categoryId}
        // 如果是更新 则要提供一个product._id为后面api判断
        if(this.isUpdate){
            product._id = this.product._id
        }
        console.log(product)
        //  调用接口函数去添加/更新
        const result = await reqAddUpdateProduct(product)
        console.log(result)
        // 根据结果提示
        if(result.status===0){
            message.success(`${this.isUpdate?'更新':'添加'}商品成功！`)
            this.props.history.goBack()
        }else{
            message.error(`${this.isUpdate?'更新':'添加'}商品失败！`)
        }
    }
    
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo)
    }

    onChange = (value, selectedOptions) => {
        // console.log(value, selectedOptions)
    }
    
    loadData =async selectedOptions => {
        // 得到选择的option对象
        const targetOption = selectedOptions[selectedOptions.length - 1];
        // 等待加载二级列表loading
        targetOption.loading = true;
        // 根据选中的分类，请求获取二级分类列表
        const subCategories = await this.getCategorys(targetOption.value)
        if(subCategories&&subCategories.length>0){
            const childOptions = subCategories.map(op=>({
                value:op._id,
                label:op.name,
                isLeaf:true
        }))
        // 设置为父分类的子分类
        targetOption.children = childOptions
        }else{
            targetOption.isLeaf=true
        }
        targetOption.loading = false
        this.setState({
            options: [...this.state.options],
          })
    }
  
    render() {
        const {isUpdate,product} = this
        const {pCategoryId,categoryId,name,price,imgs,desc,detail} = product
        // console.log(product);
        // 用来接收级联分类ID的数组
        const categoryIds = []
        // 用value去对应label
        if(isUpdate) {
        // 商品是一个一级分类的商品
        if(pCategoryId==='0') {
            categoryIds.push(categoryId)
        } else {
            // 商品是一个二级分类的商品
            categoryIds.push(pCategoryId)
            categoryIds.push(categoryId)
        }
        }
        // 指定item布局的配置对象
        const formItemLayout={
            labelCol:{span:2},//指定左侧label宽度
            wrapperCol:{span:8}//指定右侧包裹宽度
        }
        const title = (
            <span>
               <LinkButton>
                    <LeftOutlined onClick={()=>this.props.history.goBack()} style={{color:'blue',marginRight:15,fontSize:20}}/>
                </LinkButton>
                <span>{ isUpdate?'修改商品':'添加商品' }</span>
            </span>
        )
        return (
           <Card title={title}>
               <Form  {...formItemLayout} onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}  initialValues={{name,price,desc,classfy:categoryIds}} >
                   <Form.Item required label="商品名称" name='name'  rules={
                      [
                        ({ getFieldValue }) =>
                         ({validator(role,value){
                             if(!value){
                             return Promise.reject('商品名称不能为空')
                             }
                            //  else if(!validate_password(value)){
                            //  return Promise.reject('商品名称不正确')
                        //  }
                             return Promise.resolve()
                         }})
                    ]
                   }>
                      <Input placeholder="请输入商品名称" />
                   </Form.Item>
                   <Form.Item required label="商品描述" name='desc'>
                      <Input.TextArea placeholder="请输入商品描述" autosize={{ minRows: 2, maxRows: 6 }} /> 
                   </Form.Item>
                   <Form.Item required label="商品价格" name='price' rules={
                       [
                           ({ getFieldValue }) =>
                            ({validator(role,value){
                                if(!value){
                                return Promise.reject('商品价格不能为空')
                                }
                                // else if(!validate_password(value)){
                                // return Promise.reject('商品价格要在0-99999999之间')
                            // }
                                return Promise.resolve()
                            }})
                       ]
                   }>
                      <Input placeholder="请输入商品价格" type='number' addonAfter='元'/>
                   </Form.Item>
                   <Form.Item required label="商品分类" name='classfy' rules={
                       [
                           ({ getFieldValue }) =>
                            ({validator(role,value){
                                if(!value){
                                return Promise.reject('商品分类不能为空')
                                }
                                return Promise.resolve()
                            }})
                       ]
                   } >
                    <Cascader options={this.state.options} loadData={this.loadData} onChange={this.onChange} changeOnSelect placeholder='请选择商品分类'/>
                   </Form.Item>
                   <Form.Item label="商品图片" rules={[]}>
                        <PicturesWall ref={this.PicturesWall} imgs={imgs}/>
                    </Form.Item>
                    <Form.Item label='商品详情' labelCol={{span: 2}} wrapperCol={{span: 20}} rules={[]}>
                        <RichTextEditor ref={this.RichTextEditor} detail={detail}/>
                    </Form.Item>
                    <Form.Item >
                       <Button onClick={this.submit} type='primary' htmlType="submit">提交</Button>
                    </Form.Item>
               </Form>
           </Card>
        )
    }
}
